<template>
  <!-- 新增上传对话框 -->
  <el-dialog v-model="uploadVisible" title="视频上传" width="600px">
    <el-upload class="upload-wrapper" drag :auto-upload="false" :show-file-list="false" 
      :on-change="handleFileChange" :before-upload="beforeUpload" 
      accept="video/mp4" multiple :limit="10" ref="upload">
      <template v-if="selectedFiles.length === 0">
        <el-icon class="el-icon--upload">
          <upload />
        </el-icon>
        <div class="el-upload__text">
          将视频拖到此处，或<em>点击上传</em>
          <div class="el-upload__tip">支持MP4格式，大小不超过512MB，可多选</div>
        </div>
      </template>
      <template v-else>
        <div class="selected-files-list">
          <div v-for="(file, index) in selectedFiles" :key="file.name + index" class="selected-file-info">
            <el-icon class="el-icon--document"><document /></el-icon>
            <div class="file-details">
              <div class="file-name">{{ index + 1 }}. {{ file.name }}</div>
              <div class="file-size">{{ (file.size / 1024 / 1024).toFixed(2) }}MB</div>
            </div>
            <el-button type="text" class="change-file" @click.stop="removeFile(index)">
              <el-icon><close /></el-icon>
            </el-button>
          </div>
          <div class="upload-actions">
            <el-button type="primary" link @click="clearFiles">清空列表</el-button>
            <el-button type="primary" link @click="handleAddMore">继续添加</el-button>
          </div>
        </div>
      </template>
    </el-upload>
    <template #footer>
      <div class="dialog-footer">
        <div class="upload-progress" v-if="isUploading">
          <span>正在上传: {{ currentUploadIndex + 1 }}/{{ selectedFiles.length }}</span>
          <el-progress :percentage="uploadProgress" />
        </div>
        <div class="button-group">
          <el-button @click="uploadVisible = false" :disabled="isUploading">取消</el-button>
          <el-button type="primary" @click="submitUpload" :disabled="selectedFiles.length === 0 || isUploading">
            {{ isUploading ? '上传中...' : '开始上传' }}
          </el-button>
        </div>
      </div>
    </template>
  </el-dialog>
  <!-- 在el-dialog同级添加 -->
  <el-dialog v-model="renameVisible" title="重命名视频（新名称请以.mp4为后缀）" width="400px">
    <el-form :model="renameForm" @submit.prevent>
      <el-form-item label="新名称">
        <el-input v-model="renameForm.newName" autocomplete="off" label="cdcd" @keyup.enter.prevent="confirmRename" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="renameVisible = false">取消</el-button>
      <el-button type="primary" @click="confirmRename">确定</el-button>
    </template>
  </el-dialog>

  <div class="course-details-container">
    <el-container>
      <el-header class="header">
        <div class="header-content">
          <span class="header-title">
            <span style="padding-right:50px ;" v-if="classroomName">班级名称：{{ classroomName }}</span>
            <span>{{ classroomName ? '课程名称：' : '精品课：' }}</span>
            {{ courseDetail.courseName }}
            <el-tag v-if="!classroomId" class="ml-10" :type="getStatusType(courseDetail.status)" size="small">
              {{ courseStatusMap[courseDetail.status] }}
            </el-tag>
          </span>
          <div class="button-group">
            <el-button class="back-button" @click="uploadVideo" type="primary" v-if="courseDetail.status !== 2 && courseDetail.status !== 3">上传视频</el-button>
            <el-button class="back-button" type="success" @click="submitForReview" v-if="!classroomId && (courseDetail.status === 1 || courseDetail.status === 4)" :disabled="isSubmitting">提交审核</el-button>
            <el-button class="back-button" @click="goBack" type="primary">返回</el-button>
          </div>
        </div>
      </el-header>
      <el-main class="main">
        <!-- 其他内容 -->
        <!-- 表格 -->
        <page-container style="width: 100%;">
          <el-table :data="videoList" height="94%" style="width: 100%">
            <el-table-column align="center" width="100px" label="序号">
              <template #default="{ $index }">
                {{ (params.pageNum - 1) * params.pageSize + $index + 1 }}
              </template>
            </el-table-column>
            <el-table-column align="left" prop="videoName" :show-overflow-tooltip="true" label="视频名称" />
            <!-- <el-table-column align="left" prop="videoDuration" :show-overflow-tooltip="true" label="视频时长" /> -->
            <el-table-column prop="videoDuration" label="视频时长" align="center" :formatter="formatDuration">
            </el-table-column>
            <el-table-column align="left" prop="createTime" :show-overflow-tooltip="true" label="创建时间" />
            <el-table-column label="操作" align="center" width="180px">
              <template #default="{ row }">
                <el-button v-if="courseDetail.status !== 2 && courseDetail.status !== 3" type="text" plain @click="reName(row)">
                  重命名
                </el-button>
                <el-button type="text" plain @click="playBack(row.videoId)">
                  播放
                </el-button>
                <el-button v-if="courseDetail.status !== 2 && courseDetail.status !== 3" type="text" plain @click="deleteVideo(row.videoId)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination background layout="total, sizes, prev, pager, next, jumper" :total="total"
            v-model:current-page="params.pageNum" v-model:page-size="params.pageSize" :page-sizes="[10, 20, 30]"
            @size-change="handleSizeChange" @current-change="handleCurrentChange"
            style="margin:20px 100px 20px 0; justify-content: flex-end" />
        </page-container>
      </el-main>

    </el-container>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted, computed, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { getCourseDetailService, submitForReviewService } from "@/apis/course";
import { getVideoListService, uploadVideoService,delVideoService,reNameService } from "@/apis/video";
import router from "@/router";
// 新增上传相关代码
import { ElMessage, ElLoading, ElMessageBox } from 'element-plus'
import { Upload, Document, Close } from '@element-plus/icons-vue'
const formatDuration = (row, column, cellValue) => {
  // 1. 基础类型校验
  const duration = Number(cellValue ?? 0)
  if (isNaN(duration)) return '00:00'

  // 2. 时间计算
  const hours = Math.floor(duration / 3600)
  const minutes = Math.floor((duration % 3600) / 60)
  const seconds = Math.floor(duration % 60)

  // 3. 格式标准化
  const pad = n => n.toString().padStart(2, '0')
  return hours > 0
    ? `${pad(hours)}:${pad(minutes)}:${pad(seconds)}`
    : `${pad(minutes)}:${pad(seconds)}`
}
function goBack() {
  router.go(-1);
}

const uploadVisible = ref(false)
const selectedFiles = ref([])
const isUploading = ref(false)
const currentUploadIndex = ref(0)
const uploadProgress = ref(0)

// 替换原uploadVideo函数
function uploadVideo() {
  uploadVisible.value = true
}

const upload = ref(null)

const handleAddMore = () => {
  upload.value.handleClick()
}

const handleFileChange = (file) => {
  // 检查文件是否已经在列表中
  const isDuplicate = selectedFiles.value.some(f => f.name === file.raw.name)
  if (!isDuplicate) {
    // 检查文件大小
    const isSizeValid = file.raw.size / 1024 / 1024 < 512
    if (!isSizeValid) {
      ElMessage.error(`文件 ${file.raw.name} 超过512MB，已自动跳过`)
      return
    }
    // 将文件添加到列表末尾，保持选择顺序
    selectedFiles.value = [...selectedFiles.value, file.raw]
  }
}

const beforeUpload = (file) => {
  const validTypes = ['video/mp4']
  const isTypeValid = validTypes.includes(file.type)
  const isSizeValid = file.size / 1024 / 1024 < 512
  if (!isTypeValid) {
    ElMessage.error('仅支持MP4格式!')
    return false
  }
  if (!isSizeValid) {
    ElMessage.error('视频大小不能超过512MB!')
    return false
  }
  return true
}

// 修改刷新方法，添加保持页码的逻辑
const refreshPage = async (keepCurrentPage = true) => {
  try {
    // 获取当前页码和每页条数
    const currentPage = params.pageNum
    const pageSize = params.pageSize

    // 先获取最新的视频列表总数
    const result = await getVideoListService({
      ...params,
      pageNum: 1,  // 先查第一页获取总数
      pageSize: 1
    })
    
    // 计算最大页码
    const maxPage = Math.ceil(result.total / pageSize)
    
    // 如果当前页码大于最大页码，则调整到最后一页
    // 如果不需要保持当前页码，则回到第一页
    if (!keepCurrentPage) {
      params.pageNum = 1
    } else if (currentPage > maxPage && maxPage > 0) {
      params.pageNum = maxPage
    } else {
      params.pageNum = currentPage
    }

    // 获取课程详情和视频列表
    await Promise.all([
      getVideoList(),
      getCourseDetail()
    ])
  } catch (error) {
    ElMessage.error('刷新数据失败：' + (error.message || '未知错误'))
  }
}

const submitUpload = async () => {
  if (selectedFiles.value.length === 0) {
    ElMessage.warning('请选择上传文件')
    return
  }

  // 再次检查所有文件大小
  const invalidFiles = selectedFiles.value.filter(file => file.size / 1024 / 1024 >= 512)
  if (invalidFiles.length > 0) {
    ElMessage.error(`以下文件超过512MB，请移除后重试：\n${invalidFiles.map(f => f.name).join('\n')}`)
    return
  }

  isUploading.value = true
  currentUploadIndex.value = 0
  uploadProgress.value = 0

  try {
    // 创建一个新数组来存储上传失败的文件
    const failedFiles = []
    
    for (let i = 0; i < selectedFiles.value.length; i++) {
      currentUploadIndex.value = i
      const file = selectedFiles.value[i]
      
      const formData = new FormData()
      formData.append('file', file)
      formData.append('courseId', courseId)

      const loadingInstance = ElLoading.service({
        lock: true,
        text: `正在上传第 ${i + 1}/${selectedFiles.value.length} 个视频...`,
        background: 'rgba(0, 0, 0, 0.7)'
      })

      try {
        // 视频上传可能需要较长时间，增加错误处理
        const response = await uploadVideoService(formData)
        if (!response) {
          throw new Error('上传响应为空')
        }
        uploadProgress.value = Math.round(((i + 1) / selectedFiles.value.length) * 100)
      } catch (uploadError) {
        ElMessage.error(`第 ${i + 1} 个视频上传失败: ${uploadError.message || '服务器响应超时，请尝试上传小一点的视频'}`)
        // 将当前失败的文件和剩余文件都添加到失败列表
        failedFiles.push(file, ...selectedFiles.value.slice(i + 1))
        break // 跳出循环
      } finally {
        loadingInstance.close()
      }
    }

    // 更新文件列表，只保留上传失败的文件
    selectedFiles.value = failedFiles

    if (failedFiles.length === 0) {
      ElMessage.success('所有视频上传成功')
      uploadVisible.value = false
    } else {
      ElMessage.warning(`有 ${failedFiles.length} 个视频上传失败，请重试`)
    }

    // 上传成功后保持在当前页
    await refreshPage(true)
  } catch (error) {
    console.error('上传错误:', error)
  } finally {
    isUploading.value = false
    currentUploadIndex.value = 0
    uploadProgress.value = 0
  }
}

const route = useRoute();
const courseDetail = reactive({});
let courseId = route.query.courseId;
let classroomName = route.query.classroomName;
let classroomId = route.query.classroomId;
const isSubmitting = ref(false);

// 课程状态映射
const courseStatusMap = {
  0: '新建课程',
  1: '录制中',
  2: '待审核',
  3: '已发布',
  4: '驳回'
}

// 状态类型映射（用于设置不同颜色的标签）
const getStatusType = (status) => {
  const typeMap = {
    0: 'info',      // 灰色 - 新建课程
    1: 'warning',   // 黄色 - 录制中
    2: 'primary',   // 蓝色 - 待审核
    3: 'success',   // 绿色 - 已发布
    4: 'danger'     // 红色 - 驳回
  };
  return typeMap[status] || '';
};

async function getCourseDetail() {
  const res = await getCourseDetailService(courseId);
  Object.assign(courseDetail, res.data);
}

// 修改提交审核后的刷新逻辑
async function submitForReview() {
  try {
    isSubmitting.value = true
    await submitForReviewService(courseId)
    ElMessage.success('提交审核成功')
    courseDetail.status = 2
    // 提交审核后回到第一页
    await refreshPage(false)
  } catch (error) {
    ElMessage.error('提交审核失败：' + (error.message || '未知错误'))
  } finally {
    isSubmitting.value = false
  }
}

onMounted(() => {
  loadCourseData();
});

const params = reactive({
  pageNum: 1,
  pageSize: 10,
  courseId: courseId,
})
const videoList = ref([]) //题目列表
const total = ref(0)

async function getVideoList() {
  const result = await getVideoListService(params)
  videoList.value = result.rows
  total.value = result.total
}

// 分页
function handleSizeChange(newSize) {
  params.pageNum = 1
  getVideoList()
}

function handleCurrentChange(newPage) {
  getVideoList()
}

function playBack(videoId) {
  router.push(`/tims/playBack?videoId=${videoId}`)
}

// 修改删除方法
async function deleteVideo(videoId) {
  try {
    await ElMessageBox.confirm(
      '确定要删除该视频吗？',
      '删除提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        customClass: 'delete-confirm-dialog',
        confirmButtonClass: 'delete-confirm-button',
        cancelButtonClass: 'delete-cancel-button',
        showClose: false,
        closeOnClickModal: false,
        closeOnPressEscape: false,
        center: true
      }
    )
    
    await delVideoService(videoId)
    ElMessage.success('删除成功')
    await refreshPage(true)
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败：' + (error.message || '未知错误'))
    }
  }
}

// 重命名
// 组合式API写法
const renameVisible = ref(false)
const renameForm = reactive({
  videoId: null,
  newName: ''
})

// 打开重命名对话框
const reName = (video) => {
  renameForm.videoId = video.videoId
  renameForm.newName = video.videoName //回显
  renameVisible.value = true
}

// 提交重命名
const confirmRename = async () => {
  try {
    // const { data } = await axios.put('/api/video/rename', {
    //   videoId: renameForm.videoId,
    //   newName: renameForm.newName
    // })
    const result = await reNameService(renameForm)
    

    // 更新本地数据（网页2的视图更新方案）
    const index = videoList.value.findIndex(v => v.videoId === renameForm.videoId)
    if (index > -1) {
      videoList.value[index].videoName = renameForm.newName
    }

    ElMessage.success('重命名成功')
    renameVisible.value = false
  } catch (err) {
    ElMessage.error(err.response?.data?.message || '操作失败')
  }
}

// 移除单个文件
const removeFile = (index) => {
  selectedFiles.value.splice(index, 1)
}

// 清空文件列表
const clearFiles = () => {
  selectedFiles.value = []
}

// 加载课程数据的方法
const loadCourseData = async () => {
  try {
    // 更新courseId
    courseId = route.query.courseId;
    classroomName = route.query.classroomName;
    classroomId = route.query.classroomId;
    
    // 重置数据
    params.pageNum = 1;
    params.pageSize = 10;
    params.courseId = courseId;
    
    // 获取新的数据
    await Promise.all([
      getCourseDetail(),
      getVideoList()
    ]);
  } catch (error) {
    ElMessage.error('加载数据失败：' + (error.message || '未知错误'));
  }
};

// 监听路由参数变化
watch(
  () => route.query.courseId,
  (newCourseId, oldCourseId) => {
    if (newCourseId && newCourseId !== oldCourseId) {
      loadCourseData();
    }
  }
);
</script>

<style lang="scss" scoped>
/* 全局样式调整已移至main.scss */

/* 新增上传对话框样式 */
.upload-wrapper {
  :deep(.el-upload-dragger) {
    padding: 20px;
    background-color: #f8fafc;
    width: 100%;
    min-height: 200px;
    max-height: 400px;
    overflow-y: auto;

    .selected-files-list {
      width: 100%;

      .selected-file-info {
        display: flex;
        align-items: center;
        padding: 12px;
        background: #f0f7ff;
        border-radius: 4px;
        margin-bottom: 8px;

        &:last-child {
          margin-bottom: 0;
        }

        .el-icon--document {
          font-size: 24px;
          color: #007bff;
          margin-right: 12px;
        }

        .file-details {
          flex: 1;
          overflow: hidden;

          .file-name {
            font-size: 14px;
            color: #333;
            margin-bottom: 4px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }

          .file-size {
            font-size: 12px;
            color: #999;
          }
        }

        .change-file {
          padding: 4px;
          
          .el-icon {
            font-size: 16px;
            color: #999;
            
            &:hover {
              color: #f56c6c;
            }
          }
        }
      }

      .upload-actions {
        display: flex;
        justify-content: flex-end;
        padding: 8px 0 0;
        border-top: 1px solid #eee;
        margin-top: 8px;
        gap: 12px;
      }
    }
  }
}

.course-details-container {
  background-color: #f0f4ff;
  height: 100%;
  width: 100%;
  margin: 0;
  padding: 0;
  display: flex;
  flex-direction: column;
  overflow: hidden;

  :deep(.el-container) {
    height: 100%;
    display: flex;
    flex-direction: column;
    margin: 0;
    padding: 0;
  }

  .header {
    height: 60px;
    display: flex;
    align-items: center;
    background-color: #007bff;
    color: white;
    padding: 0;
    margin: 0;
    flex-shrink: 0;

    .header-content {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0 20px;
      width: 100%;

      .header-title {
        font-size: 20px;
        display: flex;
        align-items: center;
        
        .ml-10 {
          margin-left: 10px;
        }
      }

      .button-group {
        display: flex;

        .back-button {
          margin-left: 10px;
        }
      }
    }
  }

  .main {
    display: flex;
    justify-content: center;
    padding: 10px;
    flex: 1;
    overflow-y: auto;
    overflow-x: hidden;
    min-height: calc(100vh - 60px);

    .page-container {
      height: 100%;
      width: 100%;
      max-width: 1400px;
      background-color: white;
      border-radius: 8px;
      box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
      overflow: hidden;
      margin: 0;
      padding: 10px;

      .el-table {
        width: 100%;
        height: calc(100% - 70px) !important; /* 减去分页器高度 */
        border: none;

        .el-table-column {
          background-color: #f9f9f9; // Improve the table's visual appeal
        }
      }

      .el-pagination {
        margin: 20px 0;
        display: flex;
        justify-content: flex-end; // Align pagination to the right
        position: relative; // Ensure positioning works correctly

        .el-pagination__sizes {
          margin-right: 10px; // Add some space between size selector and pagination
        }
      }
    }
  }
}

.dialog-footer {
  .upload-progress {
    margin-bottom: 15px;
    
    span {
      display: block;
      margin-bottom: 8px;
      font-size: 14px;
      color: #606266;
    }
  }

  .button-group {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
  }
}
</style>

<style lang="scss">
// 删除确认框全局样式
.delete-confirm-dialog {
  // 确保弹窗位于页面正中间
  position: fixed !important;
  top: 50% !important;
  left: 50% !important;
  transform: translate(-50%, -50%) !important;
  margin: 0 !important;
  
  // 弹窗基础样式
  width: 400px !important;
  border-radius: 8px !important;
  background-color: #fff !important;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1) !important;
  
  .el-message-box__header {
    padding: 20px !important;
    border-bottom: 1px solid #ebeef5;
    background-color: #f8f9fa !important;
    border-radius: 8px 8px 0 0;
    
    .el-message-box__title {
      font-size: 18px !important;
      font-weight: 600 !important;
      color: #303133 !important;
    }
  }
  
  .el-message-box__content {
    padding: 30px 20px !important;
    font-size: 16px !important;
    color: #606266 !important;
    text-align: center !important;
    background-color: #fff !important;

    .el-message-box__status {
      font-size: 24px !important;
      margin-right: 10px !important;
    }
  }
  
  .el-message-box__btns {
    padding: 20px !important;
    text-align: center !important;
    background-color: #fff !important;
    border-top: 1px solid #ebeef5;
    border-radius: 0 0 8px 8px;
    
    button {
      min-width: 100px !important;
      margin: 0 10px !important;
      padding: 10px 20px !important;
      font-size: 14px !important;
      border-radius: 4px !important;
      
      &.delete-confirm-button {
        background-color: #f56c6c !important;
        border-color: #f56c6c !important;
        color: #fff !important;
        
        &:hover {
          background-color: #f78989 !important;
          border-color: #f78989 !important;
        }
        
        &:focus, &:active {
          background-color: #e64242 !important;
          border-color: #e64242 !important;
        }
      }
      
      &.delete-cancel-button {
        background-color: #fff !important;
        border-color: #dcdfe6 !important;
        color: #606266 !important;
        
        &:hover {
          color: #409eff !important;
          border-color: #c6e2ff !important;
          background-color: #ecf5ff !important;
        }
        
        &:focus, &:active {
          color: #3a8ee6 !important;
          border-color: #3a8ee6 !important;
        }
      }
    }
  }
}

// 添加遮罩层样式
.v-modal {
  background-color: rgba(0, 0, 0, 0.5) !important;
  opacity: 1 !important;
}
</style>